﻿using System.Data.Entity;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.SessionState;
using xuxuzhaozhao.Blog.Infrastructure.XuEntityFramework;
using xuxuzhaozhao.Blog.XuException;

namespace xuxuzhaozhao.Blog
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //WebApi全局异常处理
            GlobalConfiguration.Configuration.Filters.Add(new XuExceptionAttribute());

            //CodeFirst初始化数据库
            Database.SetInitializer<XuxuzhaozhaoDbContext>(new XuxuzhaozhaoDbInitializer());

            //清除返回的XML格式
            var formatter = GlobalConfiguration.Configuration.Formatters;
            formatter.XmlFormatter.SupportedMediaTypes.Clear();
            formatter.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
        }

        /// <summary>
        /// 在WebApi中启用Session
        /// </summary>
        public override void Init()
        {
            this.PostAuthenticateRequest += (sender, e) =>
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
            base.Init();
        }
    }
}
